import axios from 'axios';

import {
  createSource,
  createLayer,
  removeLayer
} from '../utils/GridStyleUtil';
import {
  initFullEvents,
  addTextFieldPropertiesToFeatures
} from '../utils/LayerUtil';
import {
  projectWebMercatorToLngLat
} from '../../../mapUtils/CoordinateUtil';
import {
  randomUUID
} from '../../../mapUtils/RandomUtil';
import {
  setCurrentStyle,
  formatDeviceFeature
} from '../../../mapUtils/StyleListUtil';
import ITool from './ITool';
import LINEAR_DEVICE from '../../../constant/LinearDevice.js';
import EventConstants from '../../../constant/EventConstants';

/**
 * 电网图层工具箱接口
 * @interface
 * @implements {ITool}
 */
class IGridTool extends ITool {
  constructor(_top, _impl) {
    super(_top, _impl);
    this.THROTTLE_DURATION = 300;
    this.id = randomUUID();
    this._refresh = null;
    this._locked = false;
    // 查询电网数据参数
    this.searchOption = {};
    // 数据过滤器
    this.dataFilter = null;
    // 图层文字过滤器
    this.labelFilter = null;
    // 保存最新一次的请求时间
    this.latestRequestTime = new Date().getTime();
    this.events = {
      click: () => {},
      dblclick: () => {},
      mousemove: () => {},
      mouseover: () => {},
      mouseout: () => {},
      datachange: () => {}
    };
    this.CancelToken = axios.CancelToken;
    this.cancel = null;
    this.outdateRequest = [];
    this.startzoom = false;
    this._zoomstart = this.zoomstart.bind(this);
    this.useNewService = false;
    this.option = {};
    this.isShow = false;
    this.dzReg = [new RegExp(/^[0-9]+(kV|KV)/), new RegExp(/变电站|用户变电站|升压站|牵引站|水电站$/)]
  }

  onAdd() {
    super.onAdd();
    this.setSearchOption({});
    this._sourceId = this.layeridPrefix + '_source_' + this.id;
    this._layerIds = [];
    this._layerIdsAll = [];
    initFullEvents(this);
    createSource(this.getMap(), this._sourceId, {
      tolerance: 0.01,
    });
  }

  onRemove() {
    super.onRemove();
  }

  appendCancelToken() {
    return new this.CancelToken((c) => {
      this.outdateRequest.push(c);
    });
  }
  /**
   * 取消过期请求
   */
  cancelOutDateRequest() {
    if (this.outdateRequest.length > 0) {
      this.outdateRequest.forEach((item) => {
        item();
      });
      this.outdateRequest = [];
    }
  }

  /**
   * 获取电网数据查询参数
   */
  getSearchOption() {
    return this.searchOption;
  }

  /**
   * 设置电网数据查询参数
   * @param {Object} option 参数配置
   */
  setSearchOption(option) {
    this.searchOption = Object.assign({}, this.searchOption, option);
  }
  /**
   * 数据过滤器
   * @param {Function} dataFilter
   */
  setDataFilter(dataFilter) {
    this.dataFilter = dataFilter;
  }

  setLabelFilter(labelFilter) {
    this.labelFilter = labelFilter;
    this._filterLabel();
  }

  _hasTextFieldProperty(layerid) {
    var layer = this.getMap().getLayer(layerid);
    return layer && layer.serialize().type === 'symbol';
  }
  _filterLabel() {
    if (this.labelFilter) {
      this._layerIdsAll.forEach((layerid) => {
        // 是否存在text-field属性
        var has = this._hasTextFieldProperty(layerid);
        if (has) {
          var expression = this.labelFilter(layerid);
          this.getMap().setLayoutProperty(layerid, 'text-field', expression);
        }
      });
    } else {
      // 默认隐藏所有图层的文字
      this._layerIdsAll.forEach((layerid) => {
        if (this.getMap().getLayer(layerid) && this._hasTextFieldProperty(layerid)) {
          this.getMap().setLayoutProperty(layerid, 'text-field', '');
        }
      });
    }
  }
  /**
   * 切换显示方案
   * @param {Number} sysDsno 显示方案编号
   */
  changeStyle(sysDsno) {
    setCurrentStyle(sysDsno);
    removeLayer(this);
    this.removeCustomLayer();
    createLayer(this);
    this.createCustomLayer();
    this.refresh();
  }

  /**
   * 锁定图层
   */
  lock() {
    this._locked = true;
  }

  /**
   * 解锁图层
   */
  unlock() {
    this._locked = false;
    this._refresh();
  }

  /**
   * 判断图层是否锁定
   */
  isLocked() {
    return this._locked;
  }

  /**
   * 刷新图层
   */
  refresh() {
    console.error('<refresh()> function need override');
  }

  /**
   * 显示图层
   */
  show(useNewService, option) {
    // TODO:暂时使用的方法
    this.useNewService = !!useNewService;
    // TODO:简化电网使用参数
    this.option = option;
    createLayer(this);
    this.createCustomLayer();
    this.setLabelFilter(null);
    this.changeLayerVisible('visible');
    this.getMap().on('zoomend', this._refresh);
    this.getMap().on('moveend', this._refresh);
    this.getMap().on('zoomstart', this._zoomstart);
    this.unlock();
    // this.refresh();
    this.getTool('PowerRangeTool').setGridTool(this.name);
    this.isShow = true;
  }

  /**
   * 隐藏图层
   */
  hide() {
    // 解绑事件
    this.getMap().off('zoomend', this._refresh);
    this.getMap().off('moveend', this._refresh);
    this.getMap().off('zoomstart', this._zoomstart);
    this.lock();
    this.getMap()
      .getSource(this._sourceId)
      .setData(turf.featureCollection([]));
    this.changeLayerVisible('none');
    this.setCurrentGridTool(null);
    this.hideRender();
    this.isShow = false;
  }
  zoomstart() {
    this.startzoom = true;
  }
  /**
   * 切换图层显示状态
   * @param {String} visibility 显示状态
   */
  changeLayerVisible(visibility) {
    let totalLayers = Object.keys(this.getMap().style._layers);
    totalLayers.forEach((layerId) => {
      if (layerId.indexOf(this.layeridPrefix) > -1) {
        if (this.getMap().getLayer(layerId)) {
          this.getMap().setLayoutProperty(
            layerId,
            'visibility',
            visibility
          );
        }
      }
    });
  }

  /**
   * 获取加载的图形数据
   */
  getRenderedFeatures() {
    return this.getMap().getSource(this._sourceId)._data;
  }

  /**
   * 创建自定义图层
   */
  createCustomLayer() {}

  /**
   * 移除自定义图层
   */
  removeCustomLayer() {}

  /**
   * 是否过期
   * @param {Number} date 现在时间
   * @ignore
   */
  _isOutDate(date) {
    return date < this.latestRequestTime;
  }

  /**
   * 采用思极地图的形式绘制图层
   * @param {Array} resList 图形数据
   * @param {Boolean} clear 是否清空已有图层信息
   * @ignore
   */
  _showBySgmapLayer(resList, clear) {
    let features = [];
    resList.forEach((res) => {
      if (res.res.resp_code !== 200) {
        // console.log("code ", res.res.resp_code);
        return;
      }
      let sblx = res.sblx;
      let datas = res.res.datas || [];
      datas.forEach((item) => {
        let shapejson = item.shapejson;
        if (shapejson) {
          item.geometry = JSON.parse(shapejson);
          item.sblx = sblx;
          item.simpleMc = item.sblx == 300000 ? item.sbmc.replace(this.dzReg[0], "").replace(this.dzReg[1], "") : item.sbmc;
          item.transSbzlx =
            item.versionid > 0 ?
            Number('8' + item.sbzlx) :
            item.sbzlx;
          // let style = getStyle(
          //   item,
          //   { zoom: this.getTool("BaseMapTool").getZoom() },
          // );
          item.fhjd ? item.fhjd = -item.fhjd : "";
          // 判断是否为线性设备（例如柱上变压器，竟要显示线，又要显示点设备）
          let linearSb = LINEAR_DEVICE.find(t => t.sbzlx == (item.sbzlx * 1));
          if (linearSb && !(item.versionid > 0)) {
            let linear = Object.assign({}, item);
            linear.transSbzlx = Number("9" + linear.transSbzlx);
            // 点设备
            let feature = null;
            // 判断点设备需要取哪个点
            if (linearSb.isLastPoint) {
              feature = formatDeviceFeature(linear, 1);
            } else {
              feature = formatDeviceFeature(linear);
            }
            features.push(feature);
            // 线设备
            let feature2 = formatDeviceFeature(item, 2);
            features.push(feature2);
          } else {
            let feature = formatDeviceFeature(item);
            features.push(feature);
          }
          console.log(item, features);
        } else {
          // this.info(item.sbzlx, item.oid, "设备无返回坐标信息");
        }
      });
    });
    if (this.searchOption.showCon) {
      var connectionFeatures = this.filterConnections(resList);
      features = features.concat(connectionFeatures);
    }
    features = addTextFieldPropertiesToFeatures(features, 'sbmc');
    var renderedFeatures = features;
    if (!clear) {
      renderedFeatures = renderedFeatures.concat(
        this.getMap().getSource(this._sourceId)._data.features
      );
    }
    // console.log("renderedFeatures", renderedFeatures);
    var featureCollection = turf.featureCollection(renderedFeatures);
    // 数据过滤器
    if (this.dataFilter) {
      featureCollection = this.dataFilter(featureCollection);
    }
    this.getMap()
      .getSource(this._sourceId)
      .setData(featureCollection);
    if (this.events.datachange) {
      this.events.datachange(featureCollection);
    }
    this.getEventBus().$emit('gridtool.datachange', featureCollection);
    this.finishRender();

  }
  _clearBeforeGrid() {

    this.getMap()
      .getSource(this._sourceId)
      .setData(turf.featureCollection([]));
  }
  /**
   * 过滤端子要素
   * @param {Array} resList 图形数据
   * @igonre
   */
  filterConnections(resList) {
    var connectionFeatures = [];
    resList
      .map((res) => res.res.datas)
      .forEach((datas) => {
        datas.map((data) => {
          var {
            connection,
            nodeShape
          } = data;
          // 判断端子信息是否正确
          if (this._isConnectionAvailable(connection, nodeShape)) {
            // 端子号处理
            var connections = connection.split(',');
            // 端子所在坐标处理，逗号分割坐标点->空格分隔xy->数字化处理
            var toNumber = (xy) => xy.split(' ').map((xory) => xory * 1);
            var nodeShapes = nodeShape
              .split(',')
              .map(toNumber);
            // 添加端子
            for (let idx = 0; idx < connections.length; idx++) {
              const connectionLable = connections[idx];
              const connectionPoint = nodeShapes[idx];
              // 添加端子元素
              var connectionFeature = turf.point(
                projectWebMercatorToLngLat(connectionPoint)
              );
              connectionFeature.properties = data;
              connectionFeature.properties.sbmc = connectionLable;
              connectionFeature.properties.textColor = '#000000';
              connectionFeature.properties.sourceType =
                'ConnectionLabel';
              connectionFeatures.push(connectionFeature);
            }
          }
        });
      });
    return connectionFeatures;
  }

  /**
   * 判断端子信息是否正确
   * @param {*} connection 端子
   * @param {*} nodeShape 端子坐标
   */
  _isConnectionAvailable(connection, nodeShape) {
    if (!connection || !nodeShape) {
      return false;
    }
    if (connection.split(',').length === nodeShape.split(',').length) {
      return true;
    }
    return false;
  }

  finishRender() {
    this.eventEmitter.emit(EventConstants.GRID_RENDERED, this.name, this);
  }

  hideRender() {
    this.eventEmitter.emit(EventConstants.GRID_HIDE, this.name, this);
  }
}

export default IGridTool;